package com.akuhome.resource.service.entity;

import com.akuhome.resource.DO.need.AccNeed;
import com.akuhome.resource.DO.need.AccNeedDetail;
import com.akuhome.resource.dao.DormitoryDao;
import com.akuhome.resource.entity.Dormitory;
import com.akuhome.resource.service.need.AccNeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DormitoryService {
    @Autowired
    DormitoryDao dormitoryDao;
    @Autowired
    AccNeedService accNeedService;

    public List<Dormitory> findAllDormitory(){
        return dormitoryDao.findAllDormitory();
    }

    public List<Dormitory> findDormitoryByBuildId(Integer buildId){
        return dormitoryDao.findDormitoryByBuildId(buildId);
    }

    public void insertDormitoryList(List<Dormitory> dormitoryList,Integer buildId){
        Map<String,Object> insertMap = new HashMap<>();
        insertMap.put("id",buildId);
        insertMap.put("dormList",dormitoryList);
        dormitoryDao.insertDormitoryList(insertMap);
    }
    public void updateDormitoryList(List<Dormitory> dormList){
        dormitoryDao.updateDormitoryList(dormList);
    }

    public void deleteDormitoryByBuildId(Integer buildId){
        dormitoryDao.deleteDormitoryByBuildId(buildId);
    }

    public List<Dormitory> findRestDormitoryInDate(Date date){
        List<Dormitory> dormitoryList = dormitoryDao.findAllDormitory();
        List<AccNeedDetail> accNeedDetailList = accNeedService.findAccNeedDetailInDate(date);
        checkRest(dormitoryList,accNeedDetailList);
        return dormitoryList;
    }

    private void checkRest(List<Dormitory> dormitoryList,List<AccNeedDetail> accNeedDetailList){
        dormitoryList.forEach((dorm)->{
            accNeedDetailList.forEach((acc)->{
                if(dorm.getBuild().getId().equals(acc.getBuild().getId()) && dorm.getRoomType().equals(acc.getRoomType())){
                    dorm.setAmount(dorm.getAmount()-1);
                }
            });
        });
    }
}
